﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SystemCenterSoa.BaseLibrary.Tools.TypeTools;
using SystemCenterSoa.DtoModel.Common;
using SystemCenterSoa.DtoModel.SystemManager;
using SystemCenterSoa.IRepository.SystemManager;
using SystemCenterSoa.PoModel.SystemManager;
using SystemCenterSoa.Repository.CommonLib;

namespace SystemCenterSoa.Repository.SystemManager
{
    public class AdminUserRepository : BaseRepository, IAdminUserRepository
    {
        //注入ef的的上下文
        public AdminUserRepository(SystemCenterDbSoaContext systemCenterDbSoaContext) :base(systemCenterDbSoaContext)
        {


        }
        public AdminUserPo GetAdminUserByUserName(string userName)
        {
            if (string.IsNullOrWhiteSpace(userName)) return null;
           return _systemCenterDbSoaContext.AdminUserPo.FirstOrDefault(c => c.user_name == userName);
        }
        public AdminUserDto GetAdminUserViewByUserName(string userName)
        {
            if (string.IsNullOrWhiteSpace(userName)) return null;
            var dbUser = GetAdminUserByUserName(userName);
            if (dbUser == null) return null;
            AdminUserDto view = ModelCopier.CreateInstanceFrom<AdminUserDto>(dbUser);
            view.roles = (from r in _systemCenterDbSoaContext.RolePo
                          join aur in _systemCenterDbSoaContext.AdminUserRoleRelationPo on r.role_id equals aur.role_id
                          where aur.user_name == userName
                          select r).ToList();
            if (view.roles != null && view.roles.Count > 0)
                view.roleIds = view.roles.Select(c => c.role_id).ToList();
            return view;
        }
        public bool AdminUserAdd(AdminUserDto view)
        {
            using (var tran = _systemCenterDbSoaContext.Database.BeginTransaction())
            {
                try
                {
                    AdminUserPo dbModel = ModelCopier.CreateInstanceFrom<AdminUserPo>(view);
                    _systemCenterDbSoaContext.AdminUserPo.Add(dbModel);
                    List<AdminUserRoleRelationPo> arrs = new List<AdminUserRoleRelationPo>();
                    if (view.roleIds != null && view.roleIds.Count > 0)
                    {
                        foreach (var roleId in view.roleIds)
                        {
                            arrs.Add(new AdminUserRoleRelationPo()
                            {
                                user_name = dbModel.user_name,
                                role_id = roleId,
                                creator_date = dbModel.creator_date,
                                creator_name = dbModel.creator_name
                            });
                        }
                        _systemCenterDbSoaContext.AdminUserRoleRelationPo.AddRange(arrs);
                       
                    }
                    _systemCenterDbSoaContext.SaveChanges(); //把用户和用户角色关系一起保存
                    tran.Commit();
                    return true;

                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    throw ex;
                }


            }
        }

        public bool AdminUserUpdate(AdminUserDto view)
        {
            if (view == null) return false;
            using (var tran = _systemCenterDbSoaContext.Database.BeginTransaction())
            {
                try
                {
                    AdminUserPo dbModel = _systemCenterDbSoaContext.AdminUserPo.FirstOrDefault(c => c.user_name == view.user_name);
                    ModelCopier.CopyModel(view, dbModel, "creator_name", "creator_date",
                        "last_lgoin_date", "last_login_ip", "pass_word");

                    string sql = "delete admin_user_role_relation where user_name=({0})";
                    _systemCenterDbSoaContext.Database.ExecuteSqlRaw(sql, view.user_name);

                    List<AdminUserRoleRelationPo> arrs = new List<AdminUserRoleRelationPo>();
                    if (view.roleIds != null && view.roleIds.Count > 0)
                    {
                        foreach (var roleId in view.roleIds)
                        {
                            arrs.Add(new AdminUserRoleRelationPo()
                            {
                                user_name = dbModel.user_name,
                                role_id = roleId,
                                creator_date = dbModel.modifi_date.Value,
                                creator_name = dbModel.modifi_name
                            });
                        }
                        _systemCenterDbSoaContext.AdminUserRoleRelationPo.AddRange(arrs);

                    }
                    _systemCenterDbSoaContext.SaveChanges(); //把用户和用户角色关系一起保存
                    tran.Commit();
                    return true;

                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    throw ex;
                }


            }
        }


        public PagerResult<AdminUserPo> SearchPage(SearchModel searchModel)
        {
            var query = _systemCenterDbSoaContext.AdminUserPo.AsQueryable();
            //判断有没有搜索条件
            if (searchModel.SearchItem != null && searchModel.SearchItem.Count > 0)
            {
                //把搜索条件拿出来
                Dictionary<string,string> tempDi = searchModel.SearchItem;

                //tempDi["user_name"]
                //搜索字段为user_name  
                string userName = "user_name";
                //判断搜索条件中是否有user_name
                if (tempDi.Keys.Contains(userName) && !string.IsNullOrEmpty(tempDi[userName]))
                {
                    //类似于like查询, 判断userName是否包含查询条件中的条件值
                    query = query.Where(c => c.user_name.Contains(tempDi[userName]));
                }
                //搜索字段为user_full_name
                string userFullName = "user_full_name";
                //判断搜索条件中是否有user_full_name
                if (tempDi.Keys.Contains(userFullName) && !string.IsNullOrEmpty(tempDi[userFullName]))
                {
                    query = query.Where(c => c.user_full_name.Contains(tempDi[userFullName]));
                }

                //user_status
                string userStatus = "user_status";
                //判断搜索条件中是否有user_status
                if (tempDi.Keys.Contains(userStatus) && !string.IsNullOrEmpty(tempDi[userStatus]))
                {
                    int tempStatus = -1;
                    if (int.TryParse(tempDi[userStatus], out tempStatus))
                    {
                        query = query.Where(c => c.user_status == tempStatus);
                    }

                }


                //begin_creator_date  创建时间时间段查询的开始时间
                string beginCreatorDate = "begin_creator_date";
                //判断搜索条件中是否有user_status
                if (tempDi.Keys.Contains(beginCreatorDate) && !string.IsNullOrEmpty(tempDi[beginCreatorDate]))
                {
                    DateTime tempCreatorDate = new DateTime() ;
                    if (DateTime.TryParse(tempDi[beginCreatorDate], out tempCreatorDate))
                    {
                        query = query.Where(c => c.creator_date >= tempCreatorDate);
                    }

                }

                //begin_creator_date  创建时间时间段查询的开始时间
                string endCreatorDate = "end_creator_date";
                //判断搜索条件中是否有user_status
                if (tempDi.Keys.Contains(endCreatorDate) && !string.IsNullOrEmpty(tempDi[endCreatorDate]))
                {
                    DateTime tempCreatorDate = new DateTime();
                    if (DateTime.TryParse(tempDi[endCreatorDate], out tempCreatorDate))
                    {
                        query = query.Where(c => c.creator_date <= tempCreatorDate);
                    }

                }

                if (!string.IsNullOrEmpty(searchModel.OrderBy))
                {
                    if (searchModel.OrderBy == "creator_date")
                    {
                        if (searchModel.OrderByType == OrderByType.ASC)
                        {
                            query = query.OrderBy(c => c.creator_date);
                        }
                        else
                        {
                            query = query.OrderByDescending(c => c.creator_date);
                        }
                    }


                    if (searchModel.OrderBy == "user_full_name")
                    {
                        if (searchModel.OrderByType == OrderByType.ASC)
                        {
                            query = query.OrderBy(c => c.user_full_name);
                        }
                        else
                        {
                            query = query.OrderByDescending(c => c.user_full_name);
                        }
                    }
                }

               
            }
            return BasePageSearch(query, searchModel);
        }

        public bool AdminUserPwdUpdate(string pwd, string userName)
        {
            AdminUserPo dbModel = _systemCenterDbSoaContext.AdminUserPo.FirstOrDefault(c => c.user_name == userName);
            dbModel.pass_word = pwd;
            return _systemCenterDbSoaContext.SaveChanges() > 0;

        }
    }
}
